//
//  WHAppDelegate+PushService.m
//  BinFengExpressOwner
//
//  Created by 邓伟浩 on 2018/11/7.
//  Copyright © 2018年 BinFeng. All rights reserved.
//

#import "WHAppDelegate+PushService.h"

@implementation WHAppDelegate (PushService)

- (void)setUpJPushServiceWithOptions:(NSDictionary *)launchOptions {
    /** 推送 */
    [self setUpJPushWithOptions:launchOptions];
}

- (void)setUpJPushWithOptions:(NSDictionary *)launchOptions {
    [JPUSHService setLogOFF];
    NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (remoteNotification != nil) {
        [self gridNotiWithUserInfo:remoteNotification];
    }
    
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
#if DEBUG
    [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey
                          channel:nil
                 apsForProduction:NO
            advertisingIdentifier:nil];
#else
    [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey
                          channel:nil
                 apsForProduction:YES
            advertisingIdentifier:nil];
#endif
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0) {
            DLog(@"registrationID获取成功：%@", registrationID);
        }
        else{
            DLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    /** 自定义消息 */
    [self setUpReceiveMessageNotification];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    DLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [self gridNotiWithUserInfo:userInfo];
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    DLog(@"iOS7及以上系统，收到通知:%@", [self logDic:userInfo]);
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}


- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
// 前台通知自动触发
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    
    NSDictionary *userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
//    [self gridNotiWithUserInfo:userInfo];
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        DLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
        
    }
    else {
        // 判断为本地通知
        DLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

// 点击通知触发
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
//    [UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber - 1;
//    [JPUSHService setBadge:[UIApplication sharedApplication].applicationIconBadgeNumber];
    
    [self gridPushAction:userInfo];
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        DLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
    }
    else {
        // 判断为本地通知
        DLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str = [NSPropertyListSerialization propertyListFromData:tempData
                                                     mutabilityOption:NSPropertyListImmutable
                                                               format:NULL
                                                     errorDescription:NULL];
    return str;
}


// 获取自定义消息推送内容
// 只有在前端运行的时候才能收到自定义消息的推送。
// 从jpush服务器获取用户推送的自定义消息内容和标题以及附加字段等
- (void)setUpReceiveMessageNotification {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    if ([content isEqualToString:@"101"]) {
        //        [self gridNotiWithAlert:@"您的账号在其他设备登陆"];
    }
    //    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    //    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的Extras附加字段，key是自己定义的
    
}

//kJPFNetworkDidLoginNotification 中获取RegistrationID；


#pragma mark ———— 处理通知Tips ————
// 1.账号重复登陆 action = 101
// 2.
// 3.
// 4.

//

- (void)gridNotiWithUserInfo:(NSDictionary *)userInfo {
    if (userInfo) {
        DLog(@"%@", userInfo);
        NSString *action = [userInfo objectForKey:@"action"];
        if ([action isEqualToString:@"101"]) {
            [WHView showAlertwithTitle:@"松鼠侠登陆提醒" message:@"检测到当前账号在其他设备登陆" okAction:nil cancelAction:nil];
            if (userManager.detailUserInfo != nil) {
                DLog(@"账号重复登陆");
                [userManager logout:nil];
            }
        }
//        } else if ([action isEqualToString:@"100"]) {
//            DLog(@"收到律师回复");
//            KPostNotification(@"ReceiveNewMessage", nil);
//        } else  {
//
//        }
    }
    
}

- (void)gridPushAction:(NSDictionary *)userInfo {
    if (userInfo) {
//        NSString *action = [userInfo objectForKey:@"action"];
//        if ([action isEqualToString:@"100"]) {
//            [[UIViewController topViewController] cyl_popSelectTabBarChildViewControllerAtIndex:1 completion:^(__kindof UIViewController *selectedTabBarChildViewController) {
//
//            }];
//        } else if ([action isEqualToString:@"系统消息"]) {
//            [[UIViewController topViewController] cyl_popSelectTabBarChildViewControllerAtIndex:1 completion:^(__kindof UIViewController *selectedTabBarChildViewController) {
//                WHSystemInfoController *systemInfo = [[WHSystemInfoController alloc] init];
//                [selectedTabBarChildViewController.navigationController pushViewController:systemInfo animated:YES];
//            }];
//        } else if ([action isEqualToString:@"最新动态"]) {
//            NSDictionary *artInfo = [userInfo objectForKey:@"art"];
//
//            WHTitleDetailInfo *info = [WHTitleDetailInfo modelWithJSON:artInfo];
//
//            WHDetailViewController *detail = [[WHDetailViewController alloc] init];
//            detail.navigationItem.title = @"资讯";
//            detail.detailInfo = info;
//            [[UIViewController topViewController].navigationController pushViewController:detail animated:YES];
//        } else  {
//
//        }
    }
}

@end
